package com.example.demo.test;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: wukangrong
 * @date: 2020/4/22 14:59
 * @description:
 */
public class ProducerAndConsumerSync {
    private final int MAX_LEN = 10;
    private Queue<Integer> queue = new LinkedList<>();
    class Producer extends Thread {
        @Override
        public void run() {
            producer();
        }
        private void producer() {
            while(true) {
                synchronized (queue) {
                    System.out.println("生产者获得锁");
                    if (queue.size() == MAX_LEN) {
                        System.out.println("当前队列满");
                        try {
                            System.out.println("生产者释放锁");
                            queue.wait();
                            System.out.println("生产者重新获得锁");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.add(1);
                    System.out.println("生产者生产一条任务，当前队列长度为" + queue.size());
                    queue.notifyAll();

                }
                try {
                    Thread.sleep((int)(Math.random() * 400 + 100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Consumer extends Thread {
        @Override
        public void run() {
            consumer();
        }
        private void consumer() {
            while (true) {
                synchronized (queue) {
                    System.out.println("消费者获得锁");
                    if (queue.size() == 0) {
                        System.out.println("当前队列为空");
                        try {
                            System.out.println("消费者释放锁");
                            queue.wait();
                            System.out.println("消费者重新获得锁");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.poll();
                    System.out.println("消费者消费一条任务，当前队列长度为" + queue.size());
                    queue.notifyAll();
                }

                try {
                    Thread.sleep((int)(Math.random() * 400 + 100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        ProducerAndConsumerSync pc = new ProducerAndConsumerSync();
        Producer producer = pc.new Producer();
        Consumer consumer = pc.new Consumer();
        producer.start();
        consumer.start();
    }
}
